import { defineEventHandler, readBody, getRouterParams } from 'h3'
import { verifyToken } from '../../utils/auth'
import prisma from '../../utils/prisma'

export default defineEventHandler(async (event) => {
  try {
    // Token验证
    const authHeader = getHeader(event, 'authorization')
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      throw createError({ statusCode: 401, message: '未提供认证令牌' })
    }
    
    const token = authHeader.slice(7)
    const decoded = verifyToken(token)
    if (!decoded) {
      throw createError({ statusCode: 401, message: '令牌无效或已过期' })
    }
    
    const { id } = getRouterParams(event)
    const body = await readBody(event)
    const { username, content, type, applicationScenario, interviewFrequency, remark } = body
    
    if (!username) {
      throw createError({ statusCode: 400, message: '需要提供用户名' })
    }
    
    // 验证学习记录是否存在且属于该用户
    const user = await prisma.user.findUnique({
      where: { username },
      include: { studies: { where: { id: parseInt(id) } } }
    })
    
    if (!user) {
      throw createError({ statusCode: 404, message: '用户不存在' })
    }
    
    if (user.studies.length === 0) {
      throw createError({ statusCode: 404, message: '学习记录不存在或无权访问' })
    }
    
    // 更新学习记录
    const updatedStudy = await prisma.study.update({
      where: { id: parseInt(id) },
      data: {
        content,
        type,
        applicationScenario,
        interviewFrequency: interviewFrequency ? parseInt(interviewFrequency) : null,
        remark
      }
    })
    
    return {
      code: 200,
      message: '学习记录更新成功',
      data: updatedStudy
    }
    
  } catch (error: any) {
    console.error('更新学习记录失败:', error)
    throw createError({
      statusCode: error.statusCode || 500,
      message: error.message || '更新学习记录失败'
    })
  }
})